package com.oh.iris.server;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.oh.core.common.base.MessageService;
import com.oh.core.common.cache.RedisCache;
import com.oh.core.common.constant.CommandEnum;
import com.oh.core.common.utils.MessageUtils;
import com.oh.core.common.utils.NettyAttrUtils;
import com.oh.core.common.utils.ServiceRouteFactory;
import com.oh.core.entity.MessageEntity;
import com.oh.iris.entity.UserDetail;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 登录
 */
@Service
public class SecureService implements MessageService, InitializingBean {

    private final Logger log = LoggerFactory.getLogger(SecureService.class);

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;

    @Override
    public int handle(ChannelHandlerContext ctx, MessageEntity msg) {
        String content = new String(msg.getBody());
        String str = "";
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.parseObject(content);
        }catch (JSONException e){
            str = "参数非法，登录失败!";
            log.error(str);
            MessageUtils.sendMsgToAll(str.getBytes());
            return -2;
        }
        if(!jsonObject.containsKey("userName") || !jsonObject.containsKey("password")){
            str = "参数错误!";
            log.error(str);
            MessageUtils.sendMsgToAll(str.getBytes());
            return -1;
        }
        if(jsonObject.containsKey("userName") && jsonObject.containsKey("password")){
            String userName = jsonObject.getString("userName");
            String password = jsonObject.getString("password");
            // 登录
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userName, password);
            Authentication authentication;
            try {
                authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            }catch (BadCredentialsException e){
                log.error("用户名或密码错误！");
                MessageUtils.channelMsg(ctx.channel(),new MessageEntity(CommandEnum.MESSAGE_REQUEST.getCommand(), "用户名或密码错误！".getBytes()));
                return -2;
            }
            UserDetail user = (UserDetail) authentication.getPrincipal();
            log.info("登录-用户信息{}", JSON.toJSONString(user));
            NettyAttrUtils.putClientId(ctx.channel(), String.valueOf(user.getId()));
            String accessToken = UUID.randomUUID().toString();
            log.info("token = {}", accessToken);
            String key = "sys:access:" + user.getId() + ":" + accessToken;
            redisCache.set(key, accessToken); // 设置token
            msg.setBody("登录成功".getBytes());
            MessageUtils.channelMsg(ctx.channel(), msg);
        }
        return 0;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ServiceRouteFactory.register(CommandEnum.LOGIN_REQUEST.getCommand(), this);
    }
}
